package com.genius.adminmanager.other.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.adminmanager.other.entity.SessionJson;
import com.genius.adminmanager.role.entity.RoleJson;
import com.genius.adminmanager.role.service.RoleService;
import com.genius.adminmanager.user.entity.UserJson;
import com.genius.workflow.ehcache.CacheUtils;
import com.genius.workflow.log.ControllerLog;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.DBTools;
import com.genius.workflow.util.DBUtils;
import com.genius.workflow.util.PasswordMD5;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

import java.sql.SQLException;

/**
* @Author: woy
* @Description: 当前登录用户控制器
* @Date: Created in 2020/2/3 19:28
* @param 
*/
@Controller
@RequestMapping("/adminmanager")
public class AdminimanagerLoginController {
	/**
	 * 跳转到登录页面
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/login")
	public String toLogin(){
		return "/views/adminmanager/login";
	}
	/**
     * 用户登录请求
     * @return
     */
	@ControllerLog(description="管理员后台登录系统")
    @ResponseBody
    @PostMapping("/login")
    public JSONObject login(@RequestBody JSONObject json, HttpSession session){
    	JSONObject response = new JSONObject();
    	response.put(ResponseJson.code, ResponseJson.codeSuccess);
    	
    	if(StringUtils.isEmpty(json.getString(UserJson.vercode))){
    		response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_Code_Null);
    		return response;
    	}
    	if(!session.getAttribute("checkcode").equals(json.getString(UserJson.vercode))){
    		response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_Code_Error);
    		return response;
    	}
		Subject subject=SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken(json.getString(UserJson.username),json.getString(UserJson.password));
		try{
			subject.login(token); // 登录认证
			JSONObject userJson = (JSONObject) SecurityUtils.getSubject().getPrincipal();
			//如果是admin，说明是超级用户，不再进行授权，直接登录
			JSONArray jiaoList = new JSONArray();
			String userName = userJson.getString(UserJson.username);
			if("admin".equals(userName)){
				JSONObject adminJson = new JSONObject();
				adminJson.put(RoleJson.roleId,"1");
				adminJson.put(UserJson.userId,"000");
				jiaoList.add(adminJson);
			}else{
				//根据用户查找相应的角色
				String whereField = UserJson.userId;
				String field = RoleJson.roleId+","+RoleJson.name;
				String table = "SELECT a.roleId,a.userId,b.name FROM t_user_role a left join t_role b on a.roleId=b.roleId";
				String jiaoseSql = DBTools.getSelectAndWhereSql(field, table,whereField);
				String [] jiaoseParms = DBTools.getSelectParms(whereField, userJson);

				jiaoList = DBUtils.selectArr(jiaoseSql, jiaoseParms);
			}
			if(jiaoList.size()==0){
				response.put(ResponseJson.status, ResponseJson.status_Failed);
				response.put(ResponseJson.msg, ResponseJson.msg_No_Role);
				return response;
			}else if(jiaoList.size()>1){
				response.put(ResponseJson.status, ResponseJson.status_More_Role);
				response.put(ResponseJson.msg, ResponseJson.msg_More_Role);
				JSONObject resultJson = new JSONObject();
				response.put(ResponseJson.data, resultJson);
				resultJson.put("roles", jiaoList);
				resultJson.put(UserJson.command, userJson.getString(UserJson.command));
				
				return response;
			}else{
				response.put(ResponseJson.status, ResponseJson.status_Success);
//				session.setAttribute(SessionJson.currentUser, userJson);
//				session.setAttribute(SessionJson.roleId,jiaoList);
				response.put(ResponseJson.data, userJson.getString(UserJson.command));
				RoleService.changeRoleSuccess(session, userJson, jiaoList.getJSONObject(0).getString(RoleJson.roleId));
				
			}
			return response;
		}catch(Exception e){
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Login_Pwd_Error);
			return response;
		}
    }

	/**
	 * 安全退出
	 *
	 * @return
	 * @throws Exception
	 */
	@ControllerLog(description="管理员后台退出系统")
	@GetMapping("/logout")
	public String logout() {
		JSONObject userJson = (JSONObject) SecurityUtils.getSubject().getPrincipal();
		
		String userId = userJson.getString(UserJson.userId);
		CacheUtils.cacheUtils().removeCache(userId);
		SecurityUtils.getSubject().logout();
		return "redirect:/tologin";
	}
	//跳转到修改密码页面
    @RequestMapping("/toUpdatePassword")
    public String toUpdatePassword() {
        return "/views/adminmanager/password";
    }

    //修改密码
    @ControllerLog(description="修改密码")
    @ResponseBody
    @PostMapping("/updatePassword")
    public JSONObject updatePassword(@RequestBody JSONObject json,HttpSession session) {
        JSONObject response = new JSONObject();
        response.put(ResponseJson.code, "0");
        if(json==null){
        	response.put(ResponseJson.status, 1000);
        	response.put(ResponseJson.msg, "设置失败，缺乏字段信息");
        	return response;
        }
        JSONObject userJson = (JSONObject)session.getAttribute(SessionJson.currentUser);
        String userName = userJson.getString(UserJson.username);
        String oldPwd = json.getString(UserJson.oldPassword);
		String oldMdtPwd = PasswordMD5.MD5Pwd(userName, oldPwd);

		String pwd = json.getString(UserJson.repassword);
		String mdtPwd = PasswordMD5.MD5Pwd(userName, pwd);

        if(!StringUtils.equals(oldMdtPwd, userJson.getString(UserJson.password))){
        	response.put(ResponseJson.msg, ResponseJson.msg_Old_Pwd_Error);
        	response.put(ResponseJson.status, ResponseJson.status_Failed);
        	return response;
        }
        String updateField = UserJson.password;
        String whereField = UserJson.userId;
        
        json.put(UserJson.password, mdtPwd);
        json.put(UserJson.userId, userJson.getString(UserJson.userId));
        String table = "t_user";
        try {
			DBTools.update(updateField, whereField, table, json);
			response.put(ResponseJson.msg, ResponseJson.msg_Pwd_Success);
        	response.put(ResponseJson.status, ResponseJson.status_Success);
			userJson.put(UserJson.password, json.getString(UserJson.password));
			session.setAttribute(SessionJson.currentUser, userJson);
		} catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
		}
        return response;
    }
    /**
	 * 后台首页
	 * @param roleId
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/welcome")
	public String welcome(Integer roleId)throws Exception{
		
		return "/views/adminmanager/welcome";
	}
}
